import { defineStore } from "pinia";
import { IProduct, buyProducts } from "../api/shop";
import { useProductStore } from "./product";

const productStore = useProductStore();

// {id,title,price,quantity}
type CartProduct = {
  quantity: number;
} & Omit<IProduct, "inventory">;

export const useCartStore = defineStore("cart", {
  state: () => {
    return {
      cartProoducts: [] as CartProduct[], //购物车列表
      checkoutSatus: null as null | string,
    };
  },
  getters: {
    totalPrice(state) {
      return state.cartProoducts.reduce((total, item) => {
        return (total += item.price * item.quantity);
      }, 0);
    },
  },
  actions: {
    addProductToCart(product: IProduct) {
      // 看商品有没有库存
      if (product.inventory < 1) {
        return;
      }
      // 检查购物车中是否已有该商品
      const cartItem = this.cartProoducts.find(
        (item) => item.id === product.id
      );
      // 如果有则让商品的数量加1
      if (cartItem) {
        cartItem.quantity++;
      } else {
        // 没有则添加到购物车列表
        this.cartProoducts.push({
          id: product.id,
          title: product.title,
          price: product.price,
          quantity: 1,
        });
      }
      // 并且库存减1
      productStore.decrementProduct(product);
    },
    async checkout() {
      const ret = await buyProducts();
      this.checkoutSatus = ret ? "成功" : "失败";
      if (ret) {
        this.cartProoducts = [];
      }
    },
    // 删除购物车
    delCartToProduct(product: CartProduct) {
      // 购物车删除掉该条数据
      this.cartProoducts.splice(
        this.cartProoducts.findIndex((item) => item.id === product.id),
        1
      );
      // 库存数量加list.quantity
      return productStore.addProduct(product.quantity, product.id);
    },
    // 购物车减1
    subProductToCart(product: CartProduct) {
      // 若<=1 则调用删除方法 delCartToProduct
      if (product.quantity <= 1) {
        console.log("进来了");
        return this.delCartToProduct(product);
      }
      //否则  购物车中掉该条数据-1
      //   库存数量+1
      else {
        const ret = this.cartProoducts.find((item) => item.id === product.id);
        if (ret) {
          ret.quantity--;
          productStore.addProduct(1, product.id);
        }
      }
    },
  },
});
